﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Analysis.SimpleLayer;
using Analysis.Business;
using DevExpress.XtraPrinting;

namespace Analysis
{
    public partial class frmStandartViewer : XtraForm
    {
        public DataTable DataSource
        {
            get
            {
                return dataGrid.DataSource as DataTable;
            }
            set
            {
                dataGrid.DataSource = value;
                gridView1.BestFitColumns();
                gridView1.OptionsBehavior.Editable = true;

                for (int i = 1; i < gridView1.Columns.Count; i++)
                {
                    if (gridView1.Columns[i].Name.IndexOf("Kesilsin") > -1)
                    {
                        gridView1.Columns["Kesilsin"].OptionsColumn.AllowEdit = true;
                    }
                    else if (gridView1.Columns[i].Name.IndexOf("id") > -1)
                    {
                        gridView1.Columns["id"].Visible = false;
                    }
                    else if (gridView1.Columns[i].Name.IndexOf("cari_EMail") > -1)
                    {
                        gridView1.Columns["cari_EMail"].Visible = false;
                    }
                    else
                    {
                        gridView1.Columns[i].OptionsColumn.AllowEdit = false;
                    }
                }

                for (int i = 0; i < gridView1.Columns.Count; i++)
                {
                    if (gridView1.Columns[i].ColumnType == typeof(double))
                    {
                        gridView1.Columns[i].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                        gridView1.Columns[i].DisplayFormat.FormatString = "c2";
                    }
                }
            }
        }
        public frmStandartViewer()
        {
            InitializeComponent();
        }

        private void frmStandartViewer_Load(object sender, EventArgs e)
        {

        }

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (gridView1.FocusedRowHandle > -1)
            {
                int id = Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["id"]));
                frmFaturaDetay detay = new frmFaturaDetay();
                detay.CharID = id;
                detay.ShowDialog(this);
            }
        }

        string faturaDetayToHtml(int id)
        {
            StringBuilder html = new StringBuilder();

            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT     st.sto_kod AS [Stok Kodu], st.sto_isim AS [Stok Adı], CAST(fd.sth_miktar AS decimal(16, 4)) AS Miktar,CAST(fd.sth_fiyat AS decimal(16, 4)) AS [Fatura Fiyatı],CAST(fd.fark_tutari / fd.sth_miktar AS decimal(16, 4)) AS [Fiyat Farkı],CAST(fd.fark_tutari AS decimal(16, 4)) AS [Fark Tutarı], DEPOLAR.dep_adi AS Depo \r\n");
            sb.Append(" FROM         FIYAT_FARKI_FATURA_DETAYLARI as fd INNER JOIN STOKLAR as st ON fd.sto_RECno = st.sto_RECno INNER JOIN DEPOLAR ON fd.depo_no = DEPOLAR.dep_no \r\n");
            sb.Append(" WHERE     (fd.cha_RECno = {0}) \r\n");
            DataTable dt = Factory.GetFactory.ExecuteDataTable(string.Format(sb.ToString(), id));

            html.Append(@"<tr style=""background-color: Lime; color: Maroon""> <td  style=""background-color: White; color: White""> </td> <td "">Stok Kodu</td>    <td style=""width: 400px"">Stok Adı</td>    <td>Miktar</td>    <td>Fatura Fiyatı</td>   <td>Fiyat Farkı</td>    <td>Fark Tutarı</td>    <td>Depo</td> </tr>");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                html.Append(@"<tr style=""background-color: Blue; color: White""> <td style=""background-color: White; color: White""> </td> <td>" + arrangeRight(dt.Rows[i]["Stok Kodu"], 11) + "</td> <td>" + arrangeRight(dt.Rows[i]["Stok Adı"], 25) + "</td> <td>" + arrangeRight(dt.Rows[i]["Miktar"], 10) + "</td> <td>" + arrangeRight(dt.Rows[i]["Fatura Fiyatı"], 10) + "</td> <td>" + arrangeRight(dt.Rows[i]["Fiyat Farkı"], 25) + "</td> <td>" + arrangeRight(dt.Rows[i]["Fark Tutarı"], 30) + "</td> <td>" + arrangeLeft(dt.Rows[i]["Depo"], 13) + "</td> </tr>");
            }
            return html.ToString();
        }

        string arrangeRight(object value, int len)
        {
            string sonuc = string.Empty;
            if (value.ToString().Length > len)
                sonuc = value.ToString().Substring(0, len);
            else
            {
                sonuc = value.ToString();
                for (int i = 0; i < len - value.ToString().Length; i++)
                    sonuc += " ";
            }
            return sonuc + "\t";
        }

        string arrangeLeft(object value, int len)
        {
            string sonuc = string.Empty;
            if (value.ToString().Length > len)
                sonuc = value.ToString().Substring(0, len);
            else
            {
                string bosluk = string.Empty;
                for (int i = 0; i < len - value.ToString().Length; i++)
                    bosluk += " ";
                sonuc = bosluk + value.ToString();
            }
            return sonuc + "\t";
        }

        private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            bool detayli = false;
            if (MessageBox.Show("Detaylı Gönderilsin", "Bilgi", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                detayli = true;
            }

            Dictionary<string, StringBuilder> mailSender = new Dictionary<string, StringBuilder>();
            DataTable dt = dataGrid.DataSource as DataTable;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (Convert.ToBoolean(dt.Rows[i]["Kesilsin"]) == true)
                {
                    if (mailSender.ContainsKey(dt.Rows[i]["cari_EMail"].ToString()))
                    {
                        StringBuilder sb = mailSender[dt.Rows[i]["cari_EMail"].ToString()];
                        sb.Append(@"<tr style=""background-color: Yellow; color: Maroon""> <td>" + arrangeRight(dt.Rows[i]["Belge Tarihi"], 11) + "</td> <td>" + arrangeRight(dt.Rows[i]["Belge No"], 10) + "</td> <td>" + arrangeRight(dt.Rows[i]["Fatura Seri"], 10) + "</td> <td>" + arrangeRight(dt.Rows[i]["Fatura Sıra"], 10) + "</td> <td>" + arrangeRight(dt.Rows[i]["Cari Kodu"], 25) + "</td> <td>" + arrangeRight(dt.Rows[i]["Cari Ünvanı"], 30) + "</td> <td>" + arrangeLeft(dt.Rows[i]["Fatura Tutarı"], 13) + "</td> <td>" + arrangeLeft(dt.Rows[i]["Fiyat Farkı Tutarı"], 18) + "</td> </tr>");
                        if (detayli)
                            sb.Append(faturaDetayToHtml(Convert.ToInt32(dt.Rows[i]["id"])));
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append(@"<tr style=""background-color: Yellow; color: Maroon""> <td>" + arrangeRight(dt.Rows[i]["Belge Tarihi"], 11) + "</td> <td>" + arrangeRight(dt.Rows[i]["Belge No"], 10) + "</td> <td>" + arrangeRight(dt.Rows[i]["Fatura Seri"], 10) + "</td> <td>" + arrangeRight(dt.Rows[i]["Fatura Sıra"], 10) + "</td> <td>" + arrangeRight(dt.Rows[i]["Cari Kodu"], 25) + "</td> <td>" + arrangeRight(dt.Rows[i]["Cari Ünvanı"], 30) + "</td> <td>" + arrangeLeft(dt.Rows[i]["Fatura Tutarı"], 13) + "</td> <td>" + arrangeLeft(dt.Rows[i]["Fiyat Farkı Tutarı"], 18) + "</td> </tr>");
                        if (detayli)
                            sb.Append(faturaDetayToHtml(Convert.ToInt32(dt.Rows[i]["id"])));
                        mailSender.Add(dt.Rows[i]["cari_EMail"].ToString(), sb);
                    }
                }
            }

            foreach (string key in mailSender.Keys)
            {
                eMail mail = new eMail();
                StringBuilder sb = new StringBuilder();
                sb.Append("<p>Sayın Yetkili;</p>");
                sb.Append("<p>Aşağıda Listelediğimiz Faturaların tedarik sürecinde yaptığımız anlaşmalar ve siparişlerle </p>");
                sb.Append("<p>farklılıklar görülmüş ve sistemimiz tarafından aşağıda belirlenen tutarlarda fiyat farkı kesilmesi </p>");
                sb.Append("<p>öngörülmüştür.</p>");
                sb.Append("<p>Kesilmesi Gereken Fiyat Farkı Faturaları :</p>");
                sb.Append(@"<table width=""1000"" border=""1"">  <tr style=""background-color: Gray; color: White""> <td>Belge Tarihi</td>    <td>Belge No</td>    <td>Evrak Seri</td>    <td>Evrak Sıra</td>   <td>Firma Kodu</td>    <td>Firma Ünvanı</td>    <td>Fatura Tutarı</td>    <td>Fiyat Farkı Tutarı</td>  </tr>");
                string mesaj = sb.ToString() + mailSender[key].ToString() + "</table>";

                if (Config.GetConfig.GetValue(Parametre.ServerType) == "Gmail")
                {
                    mail.Gmail(Config.GetConfig.GetValue(Parametre.email), key, Config.GetConfig.GetValue(Parametre.mailUser), Config.GetConfig.GetValue(Parametre.emailPwd), "Bilgilendirme!", mesaj, Config.GetConfig.GetValue(Parametre.smtpServer));
                }
                else
                {
                    mail.Smtp(Config.GetConfig.GetValue(Parametre.email), key, Config.GetConfig.GetValue(Parametre.mailUser), Config.GetConfig.GetValue(Parametre.emailPwd), "Bilgilendirme!", mesaj, Config.GetConfig.GetValue(Parametre.smtpServer));
                }
            }
        }

        DataTable faturaDetayToDataTable(int id)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("SELECT   {0} as id, st.sto_isim AS [Stok Adı], CAST(fd.sth_miktar AS decimal(16, 4)) AS Miktar,CAST(fd.sth_fiyat AS decimal(16, 4)) AS [Fatura Fiyatı],CAST(fd.fark_tutari / fd.sth_miktar AS decimal(16, 4)) AS [Fiyat Farkı],CAST(fd.fark_tutari AS decimal(16, 4)) AS [Fark Tutarı], DEPOLAR.dep_adi AS Depo \r\n", id);
            sb.Append(" FROM         FIYAT_FARKI_FATURA_DETAYLARI as fd INNER JOIN STOKLAR as st ON fd.sto_RECno = st.sto_RECno INNER JOIN DEPOLAR ON fd.depo_no = DEPOLAR.dep_no \r\n");
            sb.Append(" WHERE     (fd.cha_RECno = {0}) \r\n");
            DataTable dt = Factory.GetFactory.ExecuteDataTable(string.Format(sb.ToString(), id));
            return dt;
        }

        private void masterDetail()
        {
            DataTable dt = (dataGrid.DataSource as DataTable).Copy();
            dt.TableName = "ust";
            List<DataRow> removeRows = new List<DataRow>();

            DataTable tmp = new DataTable("hareket");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (Convert.ToBoolean(dt.Rows[i]["Kesilsin"]) == true)
                {
                    DataTable d = faturaDetayToDataTable(Convert.ToInt32(dt.Rows[i]["id"]));
                    if (tmp.Columns.Count == 0)
                        for (int c = 0; c < d.Columns.Count; c++)
                        {
                            tmp.Columns.Add(d.Columns[c].ColumnName, d.Columns[c].DataType);
                        }
                    for (int x = 0; x < d.Rows.Count; x++)
                    {
                        tmp.ImportRow(d.Rows[x]);
                    }
                }
                else
                {
                    removeRows.Add(dt.Rows[i]);
                }
            }
            foreach (DataRow r in removeRows)
            {
                dt.Rows.Remove(r);
            }

            DataSet sonuc = new DataSet();
            sonuc.Tables.Add(dt);
            sonuc.Tables.Add(tmp);
            sonuc.Relations.Add("sonuc", sonuc.Tables["ust"].Columns["id"], sonuc.Tables["hareket"].Columns["id"]);
            gridControl1.DataSource = sonuc.Tables["ust"];
            gridView3.Columns[0].Visible = false;
            gridView3.Columns[3].Visible = false;
            gridView3.Columns[4].Visible = false;
            gridView3.Columns[9].Visible = false;
            gridView3.Columns[10].Visible = false;
            gridView3.Columns[11].Visible = false;
            gridView3.Columns["id"].Visible = false;
            gridView3.BestFitColumns();
            gridView3.ColumnPanelRowHeight = 30;
            for (int i = 0; i < gridView3.Columns.Count; i++)
            {
                gridView3.Columns[i].AppearanceHeader.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            }
        }
        private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView vi = null;
            bool detayli = false;
            if (MessageBox.Show("Detaylı Gönderilsin", "Bilgi", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                masterDetail();
                detayli = true;
            }
            if (detayli)
                vi = gridView3;
            else
                vi = gridView1;

            vi.Columns[0].Visible = false;
            vi.Columns[3].Visible = false;
            vi.Columns[4].Visible = false;
            vi.Columns[9].Visible = false;
            vi.Columns[10].Visible = false;
            vi.Columns[11].Visible = false;

            PrintableComponentLink link = new PrintableComponentLink(new PrintingSystem());
            link.Margins.Left = 5;
            link.Margins.Right = 5;
            link.Margins.Top = 5;
            link.Margins.Bottom = 5;

            if (detayli)
                link.Component = gridControl1;
            else
                link.Component = dataGrid;

            link.CreateDocument();
            link.PrintDlg();

            vi.Columns[0].Visible = true;
            vi.Columns[3].Visible = true;
            vi.Columns[4].Visible = true;
            vi.Columns[9].Visible = true;
            vi.Columns[10].Visible = true;
            vi.Columns[11].Visible = true;
        }

        private void barButtonItem6_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView vi = null;
            bool detayli = false;
            if (MessageBox.Show("Detaylı Gönderilsin", "Bilgi", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                masterDetail();
                detayli = true;
            }
            if (detayli)
                vi = gridView3;
            else
                vi = gridView1;

            vi.Columns[0].Visible = false;
            vi.Columns[3].Visible = false;
            vi.Columns[4].Visible = false;
            vi.Columns[9].Visible = false;
            vi.Columns[10].Visible = false;
            vi.Columns[11].Visible = false;
            if (detayli)
                gridControl1.ShowPrintPreview();
            else
                dataGrid.ShowPrintPreview();
            vi.Columns[0].Visible = true;
            vi.Columns[3].Visible = true;
            vi.Columns[4].Visible = true;
            vi.Columns[9].Visible = true;
            vi.Columns[10].Visible = true;
            vi.Columns[11].Visible = true;
        }

        private void dataGrid_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control == true && e.Shift == true && e.KeyCode == Keys.Q)
            {
                new dbMikro().FaturaYenidenAktar(gridView1.GetFocusedRowCellValue(gridView1.Columns["id"]).ToString());
                MessageBox.Show("Tamam");
            }
        }
    }
}
